package com.NetSunWeiQin.chapter06.echoServer;


import java.net.*;
import java.io.*;

public class EchoClient {
    public static void main(String args[]) throws IOException


    {
        URL.setURLStreamHandlerFactory(new EchoURLStreamHandlerFactory());

        URLConnection.setContentHandlerFactory(new EchoContentHandlerFactory());

        // 如果你 把  echo  改成http则报错  sun.net.www.protocol.http.HttpURLConnection cannot be cast to com.NetSunWeiQin.chapter06.echo.EchoURLConnection
        URL url = new URL("echo://localhost:8000");

        EchoURLConnection connection = (EchoURLConnection) url.openConnection();

        connection.setDoOutput(true);

        PrintWriter pw = new PrintWriter(connection.getOutputStream(), true);

        while (true) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String msg = br.readLine();
            pw.println(msg);
            String echoMsg = (String) connection.getContent();
            System.out.println(echoMsg);
            if (echoMsg.equals("echo:bye")) {
                connection.disconnect();
                break;
            }
        }
    }
}


